<?php

namespace App\Repositories\Article;

use App\Models\Article;
use App\Repositories\BaseRepository;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Arr;

/**
 * 文章仓库类
 * Class ArticleRepository
 * @package App\Repositories\Article
 * @method Article|null getById($id)
 * @method Article create(array $attributes)
 */
class ArticleRepository extends BaseRepository
{
    public function __construct(Article $model)
    {
        parent::__construct($model);
    }

    public function paginate(array $params): LengthAwarePaginator
    {
        $query = $this->query();

        $keyword = Arr::get($params, 'keyword');
        if ($keyword) {
            $query->where('title', 'like', '%' . $keyword . '%');
        }

        $startDate = Arr::get($params, 'startDate');
        $endDate = Arr::get($params, 'endDate');

        if ($startDate && $endDate) {
            $query->where('created_at', '>=', $startDate);
            $query->where('created_at', '<=', $endDate);
        }

        return $query
            ->with('category')
            ->orderByDesc('id')
            ->paginate(10)
            ->through(fn(Article $item) => [
                'id' => $item->id,
                'title' => $item->title,
                'author' => $item->author,
                'cover' => $item->cover,
                'views' => $item->views,
                'category_name' => $item->category->name,
                'status' => $item->status,
                'is_top' => $item->is_top,
                'is_recommend' => $item->is_recommend,
                'sort' => $item->sort,
                'push_status' => $item->push_status,
                'created_at' => $item->created_at->format('Y-m-d'),
            ]);
    }
}
